/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package monitorandwebserver;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 *
 * @author rafal
 */
public class SensorsData {

    private static volatile SensorsData instance = null;

    public static SensorsData getInstance() {
        if (instance == null) {
            synchronized (SensorsData.class) {
                if (instance == null) {
                    instance = new SensorsData();
                }
            }
        }
        return instance;
    }

    private SensorsData() {
        sensors = Collections.synchronizedList(new ArrayList<Sensor>());
    }
    
    private  List<Sensor> sensors;

    synchronized public void addSensor(String metric, String mappedAddress, String ipAddress, int port) {
        sensors.add(new Sensor(metric, mappedAddress,ipAddress, port));
    }

    synchronized public Sensor getSensor(String resourceID, String metric){
        for(Sensor sensor : sensors){
            if(sensor.mappedAddress.equals(resourceID) && sensor.metric.equals(metric)){
                return sensor;
            }
        }
        return null;
    }
    
    synchronized public String readFromSensor(String mappedAddress, String metric) {
        for (Sensor sensor : sensors) {
            if (sensor.metric.equals(metric) && sensor.mappedAddress.equals(mappedAddress)) {
                return sensor.data;
            }
        }
        return "Error: Requested data from unknown sensor";
    }
    
    public boolean updateSensorData(String data, String ipAddress, int port){
        for (Sensor sensor : sensors) {
            if (sensor.port == port && sensor.ipAddress.equals(ipAddress)) {
                sensor.data = data;
                return true;
            }
        }
        return false; 
    }
}
